package TCP;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Locale;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TCPServer {
    public static void main(String[] args) throws IOException {
        //创建线程池
        ExecutorService es = Executors.newFixedThreadPool(10);

        //创建服务器
        ServerSocket serverSocket = new ServerSocket(8888);
        System.out.println("Server start");

        //等待客户端连接

        while(true) {
            Socket socket = serverSocket.accept();
            System.out.println("connected");

            //创建任务
            Runnable r = new Runnable() {
                @Override
                public void run() {
                    //获得socket输入输出流
                    try {
                        InputStream in = socket.getInputStream();
                        OutputStream out = socket.getOutputStream();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                        PrintWriter writer = new PrintWriter(out);

                        //读数据
                        String s = reader.readLine();

                        //处理数据
                        System.out.println(s);
                        writer.println(s.toUpperCase());
                        writer.flush();
                    } catch(Exception e){
                        e.printStackTrace();
                    } finally {
                        try {
                            socket.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            //把任务交给线程池
            es.submit(r);
        }

        //释放资源
        //serverSocket.close();
        //es.shutdown();
    }
}

